package minihttpserver;

import java.io.*;
import java.net.*;
import java.util.*;

public class TinyHttpdConnection extends Thread {

    Socket s;
    FileInputStream fis;

    TinyHttpdConnection(Socket s) {
        this.s = s;
        setPriority(NORM_PRIORITY - 1);
    }

    @Override
    public void run() {
        try {
            BufferedReader i = new BufferedReader(new InputStreamReader(s.getInputStream()));
            DataOutputStream o = new DataOutputStream(s.getOutputStream());

            String req = i.readLine();
            System.out.println(req);

            System.out.println(s.getLocalAddress());

            StringTokenizer sT = new StringTokenizer(req);
            if (sT.countTokens() > 1 && sT.nextToken().equals("GET")) {
                if ((req = sT.nextToken()).startsWith("/")) {
                    req = req.substring(1);
                }
                if (req.endsWith("/") || req.equals("")) {
                    req = req + "src/minihttpserver/index.html";
                }

                try {
                    //new PrintStream(o).println("GET "+req);
                    fis = new FileInputStream(req);
                    byte[] data = new byte[fis.available()];
                    fis.read(data);
                    o.write(data);
                } catch (FileNotFoundException e) {
                    new PrintStream(o).println("404 Not Found");
                }
            } else {
                if (sT.countTokens() > 1 && sT.nextToken().equals("POST")) {
                    if ((req = sT.nextToken()).startsWith("/")) {
                        req = req.substring(1);
                    }
                    if (!req.startsWith("/LOGIN")) {
                        try {
                            //new PrintStream(o).println("GET "+req);
                            fis = new FileInputStream(req);
                            byte[] data = new byte[fis.available()];
                            fis.read(data);
                            o.write(data);
                        } catch (FileNotFoundException e) {
                            new PrintStream(o).println("404 Not Found");
                        }
                    } else {
                        new PrintStream(o).println("OK");
                    }
                } else {
                    new PrintStream(o).println("400 Bad Request");
                }
            }


            s.close();
        } catch (IOException e) {
            System.out.println("I/O error " + e);
        }
    }
}
